package com.acenodie.acenodieopenglturorial.filter;

import java.nio.FloatBuffer;
import java.util.List;

import android.opengl.GLES20;


public class GPUImageGroupFilter extends GPUImageFilter{
	
    protected List<GPUImageFilter> mFilters;
    
    public GPUImageGroupFilter(List<GPUImageFilter> filters){
    	this.mFilters = filters;
    }
    
	@Override
    public void onDestroy() {
        for (GPUImageFilter filter : mFilters) {
            filter.destroy();
        }
//        destroyFramebuffers();
    }
    
    @Override
    public void init() {
        for (GPUImageFilter filter : mFilters) {
            filter.init();
            if(!filter.isInitialized()) {
            	setInitialized(false);
            	return;
            }
        }
        setInitialized(true);
    }
    
    @Override
    public void onOutputSizeChanged(final int width, final int height) {
//        super.onOutputSizeChanged(width, height);
        int size = mFilters.size();
        for (int i = 0; i < size; i++) {
            mFilters.get(i).onOutputSizeChanged(width, height);
        }
    }
    
    @Override
    public int onDrawFrame(final int textureId, final FloatBuffer cubeBuffer,
    		final FloatBuffer textureBuffer) {
    	int size = mFilters.size();
        int previousTexture = textureId;
        int processedTexture;
        
        for (int i = 0; i < size; i++) {
        	GPUImageFilter filter = mFilters.get(i);
            processedTexture = filter.onDrawFrame(previousTexture, mGLCubeBuffer, mGLTextureBuffer);
            previousTexture = processedTexture;
        }
        
    	return previousTexture;  	
    }
    
    @Override
    public int onDrawFrame(final int textureId) {
    	if (mFrameBuffers == null || mFrameBufferTextures == null) {
            return OpenGLUtils.NOT_INIT;
        }
    	int size = mFilters.size();
        int previousTexture = textureId;
        for (int i = 0; i < size; i++) {
        	GPUImageFilter filter = mFilters.get(i);
            boolean isNotLast = i < size - 1;
            if (isNotLast) {
                GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[i]);
                GLES20.glClearColor(0, 0, 0, 0);
                filter.onDrawFrame(previousTexture, mGLCubeBuffer, mGLTextureBuffer);
                GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
                previousTexture = mFrameBufferTextures[i];
            }else{
            	filter.onDrawFrame(previousTexture, mGLCubeBuffer, mGLTextureBuffer);
            }
        }
    	return OpenGLUtils.ON_DRAWN;  	
    }
    
    public int getFilterCount(){
    	return mFilters.size();
    }
    
    public void setLevel(int paramInt) {
    	for (GPUImageFilter filter : mFilters) {
            filter.setLevel(paramInt);
        }
	}
}

